import React, { useState } from 'react';
import './Login.css';

const Login = ({ onLoginSuccess }) => {
  const [isLogin, setIsLogin] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    const formData = new FormData(e.target);
    const values = Object.fromEntries(formData.entries());

    try {
      setLoading(true);
      const endpoint = isLogin ? 'login' : 'register';
      const response = await fetch(`/api/${endpoint}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '操作失败');
      }

      if (isLogin) {
        localStorage.setItem('user', JSON.stringify(data));
        onLoginSuccess(data);
      } else {
        alert('注册成功，请登录');
        setIsLogin(true);
      }
    } catch (error) {
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <h2 className="login-title">{isLogin ? '登录' : '注册'}</h2>
      <div className="tab-container">
        <button 
          className={`tab-button ${isLogin ? 'active' : ''}`}
          onClick={() => setIsLogin(true)}
        >
          登录
        </button>
        <button 
          className={`tab-button ${!isLogin ? 'active' : ''}`}
          onClick={() => setIsLogin(false)}
        >
          注册
        </button>
      </div>
      {error && <div className="error-message">{error}</div>}
      <form onSubmit={handleSubmit} className="login-form">
        <div className="form-group">
          <label htmlFor="username">用户名</label>
          <input
            type="text"
            id="username"
            name="username"
            required
            placeholder="请输入用户名"
          />
        </div>
        <div className="form-group">
          <label htmlFor="password">密码</label>
          <input
            type="password"
            id="password"
            name="password"
            required
            placeholder="请输入密码"
          />
        </div>
        {!isLogin && (
          <>
            <div className="form-group">
              <label htmlFor="amapKey">高德地图Key</label>
              <input
                type="text"
                id="amapKey"
                name="amapKey"
                required
                placeholder="请输入高德地图Key"
              />
            </div>
            <div className="form-group">
              <label htmlFor="securityJsCode">安全密钥</label>
              <input
                type="text"
                id="securityJsCode"
                name="securityJsCode"
                placeholder="请输入安全密钥"
              />
            </div>
            <div className="form-help">
              <p>请在高德开放平台获取 Key 和安全密钥：</p>
              <ol>
                <li>访问 <a href="https://console.amap.com/dev/key/app" target="_blank" rel="noopener noreferrer">高德开放平台</a></li>
                <li>创建新应用或选择现有应用</li>
                <li>添加 Key，服务平台选择 "Web端(JS API)"</li>
                <li>在 Key 详情中获取安全密钥</li>
              </ol>
            </div>
          </>
        )}
        <button 
          type="submit" 
          className="submit-button" 
          disabled={loading}
        >
          {loading ? '处理中...' : (isLogin ? '登录' : '注册')}
        </button>
      </form>
    </div>
  );
};

export default Login; 